package com.example.oa;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter("/*")
public class PseudoSignInFilter implements javax.servlet.Filter{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //1.获取资源请求的路径,强制转换
        HttpServletRequest req = (HttpServletRequest) request;
        String rString = req.getRequestURI();
        //2.有些资源需要放行
        if (rString.contains("/admin.jsp")) {
            chain.doFilter(req, response);
        } else { //3.当访问其他资源，就判断是否登录
            Object obj = req.getSession().getAttribute("user");
            if (obj != null) {  //如果有，则放行
                chain.doFilter(request, response);
            } else {  //如果没有，则跳转到登录界面
                req.setAttribute("message", "Invalid！");
                req.getRequestDispatcher("/index.jsp").forward(req, response);
            }
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}